package com.kh.pajx.sop.view.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.domain.HsEquipmentInfo;
import com.kh.pajx.sop.domain.HsSchoolInfo;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.common.ValidatorUtils;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.sop.PropertyValidate;
import com.opensymphony.xwork2.ActionContext;

/**
 * 设备信息 逻辑控制器
 * 
 * @author 马兴龙
 * @createDate 2014年6月23日 下午5:21:08
 */
@Controller
@Scope("prototype")
public class EquipmentAction extends ModelDrivenBaseAction<HsEquipmentInfo> {
    private List<HsEquipmentInfo> list;
    private HsEquipmentInfo equ;
    private String equNos;
    private String jsons;

    /**
     * 跳转到添加设备页面
     */
    public String jsp() {
	List<HsSchoolInfo> schoollist = null;
	// 获取所有学校信息
	if (getCurrentUser().isLookAll()) {
	    schoollist = schoolService.findAllSchool();
	} else {
	    schoollist = schoolService.getSclBySclIds(getCurrentUser().getSclIdList());
	}
	Map request = (Map) ActionContext.getContext().get("request");
	request.put("schoollist", schoollist);
	return "jsp";
    }

    /**
     * 查询设备信息
     */
    public String list() {
	/*try {
	    if (getCurrentUser().getSclIdList() == null || getCurrentUser().getSclIdList().size() <= 0) {
		throw new Exception("您还没有可以浏览的学校！");
	    }
	    HttpServletRequest request = ServletActionContext.getRequest();
	    String sclName = request.getParameter("model.sclName");
	    if (!PropertyValidate.validateSafeString(sclName, 30, true)) {
		throw new Exception("检索条件[学校名称]输入不符合规范！");
	    }

	    QueryHelper query = new QueryHelper(HsEquipmentInfo.class, "d");
	    query.addCondition("d.equStausFlag=?", "1");
	    if (equ != null) {
		HsSchoolInfo sch = null;
		if (StringUtils.isNotBlank(sclName)) {
		    sch = new HsSchoolInfo();
		    sch.setSclName(sclName);
		    equ.setHsSchoolInfo(sch);
		    request.setAttribute("reSclName", sclName);
		}
		if (equ.getHsSchoolInfo() != null && equ.getHsSchoolInfo().getSclName() != null && StringUtils.isNotEmpty(equ.getHsSchoolInfo().getSclName())) {
		    query.addCondition("d.hsSchoolInfo.sclName like ?", "%" + equ.getHsSchoolInfo().getSclName() + "%");
		}
		if (equ.getEquType() != null && StringUtils.isNotEmpty(equ.getEquType()) && !equ.getEquType().equals("-1")) {
		    query.addCondition("d.equType=?", equ.getEquType());
		}
		if (equ.getEquNo() != 0) {
		    query.addCondition("cast(d.equNo as string) like ?", "%" + equ.getEquNo() + "%");
		}

	    } else {

	    }
	    if (!this.getCurrentUser().isLookAll()) {
		query.addConditionWithIn("d.hsSchoolInfo.sclId", "sclIds", this.getCurrentUser().getSclIdList());
	    }
	    query.addOrderProperty("d.equNo", true);
	    query.preparePageBean(hsEquipmentInfoService, pageNum, numPerPage);
	} catch (Exception e) {
	    e.printStackTrace();
	}
*/
	return "list";

    }
    /**
     * 查询设备信息
     */
    public String show() {
	try {
	    if (getCurrentUser().getSclIdList() == null || getCurrentUser().getSclIdList().size() <= 0) {
	    	throw new Exception("您还没有可以浏览的学校！");
	    }
	    HttpServletRequest request = ServletActionContext.getRequest();
	    String sclName = request.getParameter("model.sclName");
	    if (!ValidatorUtils.validateSafeString(sclName, 30, true)) {
	    	throw new Exception("检索条件[学校名称]输入不符合规范！");
	    }
	    if(!ValidatorUtils.validateFixedLengthNumber(model.getEquType(), 1, true)){
	    	throw new Exception("检索条件[设备类型]输入不符合规范！");
	    }
	    //此处设备编号为数字且长度不定，所以只验证是否为数字，Long类型长度最大为19
	    if(!ValidatorUtils.validateNumber(Long.toString(model.getEquNo()), 19, true)){
	    	throw new Exception("检索条件[设备编号]输入不符合规范！");
	    }
	    QueryHelper query = new QueryHelper(HsEquipmentInfo.class, "d");
	    query.addCondition("d.equStausFlag=?", "1");
	    if (equ != null) {
		HsSchoolInfo sch = null;
		if (StringUtils.isNotBlank(sclName)) {
		    sch = new HsSchoolInfo();
		    sch.setSclName(sclName);
		    equ.setHsSchoolInfo(sch);
		    request.setAttribute("reSclName", sclName);
		}
		if (equ.getHsSchoolInfo() != null && equ.getHsSchoolInfo().getSclName() != null && StringUtils.isNotEmpty(equ.getHsSchoolInfo().getSclName())) {
		    query.addCondition("d.hsSchoolInfo.sclName like ?", "%" + equ.getHsSchoolInfo().getSclName() + "%");
		}
		if (equ.getEquType() != null && StringUtils.isNotEmpty(equ.getEquType()) && !equ.getEquType().equals("-1")) {
		    query.addCondition("d.equType=?", equ.getEquType());
		}
		if (equ.getEquNo() != 0) {
		    query.addCondition("cast(d.equNo as string) like ?", "%" + equ.getEquNo() + "%");
		}

	    } else {

	    }
	    if (!this.getCurrentUser().isLookAll()) {
		query.addConditionWithIn("d.hsSchoolInfo.sclId", "sclIds", this.getCurrentUser().getSclIdList());
	    }
	    query.addOrderProperty("d.equNo", true);
	    query.preparePageBean(hsEquipmentInfoService, pageNum, numPerPage);
	} catch (Exception e) {
		e.printStackTrace();
		ActionContext.getContext().put("errorMsg", "检索失败！"+e.getMessage());
	}

	return "show";

    }

    /**
     * 通过设备学校编号、设备类型查询设备编号
     */
    public void findEquNo() throws IOException {
	HttpServletRequest request = ServletActionContext.getRequest();
	// 获取学校编号和设备类型
	String sclId = request.getParameter("sclId");
	String equType = request.getParameter("equType");
	List<HsEquipmentInfo> list = hsEquipmentInfoService.findByHql(sclId, equType);
	// ActionContext.getContext().put("list", list);
	String str = "";
	// 返回结果拼成json形式
	for (int j = 0; j < list.size(); j++) {
	    str += "{" + "\"equNo\":" + "\"" + list.get(j).getEquNo() + "\"" + "}";
	    if (j != list.size() - 1) {
		str += ",";
	    }
	}
	jsons = "[" + str + "]";

	HttpServletResponse response = ServletActionContext.getResponse();
	response.setCharacterEncoding("UTF-8");
	PrintWriter out = response.getWriter();
	out.print(jsons);
	out.close();

    }

    /** 删除 */
    public void delete() {
	int delRows = hsEquipmentInfoService.deleteByequNo(equNos);
	// 设置跳转
	DwzAjaxResult result = new DwzAjaxResult();
	try {
	    result.setStatusCode("200");
	    result.setMessage("成功删除" + delRows + "条！");
	    result.setRel("show_equ_list");
	    DwzAjaxResult.josnMessage(result);

	} catch (Exception e) {
	    result.setMessage("删除失败");
	    result.setStatusCode("300");
	    DwzAjaxResult.josnMessage(result);
	}

    }

    /**
     * 添加设备信息
     * 
     */
    public void addEqu() throws IOException {
	DwzAjaxResult result = new DwzAjaxResult();
	try {
	    HttpServletRequest request = ServletActionContext.getRequest();
	    String schId = request.getParameter("model.sclId");
	    if (!ValidatorUtils.validateUUID(schId, false)) {
		throw new Exception("[学校编号]为空或不符合规范");
	    }
	    if (!ValidatorUtils.validateFixedLengthNumber(model.getEquType(), 1, false)) {
		throw new Exception("[设备类型]选择不符合规范");
	    }
	    HsSchoolInfo sch = new HsSchoolInfo();
	    // 设置设备信息的学校编号
	    sch.setSclId(schId);
	    model.setHsSchoolInfo(sch);
	    model.setCreateOperId(getCurrentUser().getUserId());
	    List<HsEquipmentInfo> hsEqu = hsEquipmentInfoService.get(model.getEquNo());
	    if (hsEqu!=null&&hsEqu.size() > 0) {
		throw new Exception("该设备流水号已经存在，请修改");
	    } 
	    // 当设备为考勤设备时
	    if ("0".equals(model.getEquType())) {
		validatePropertyByKaoQin(model);
		hsEquipmentInfoService.add(model);
		result.setStatusCode("200");
		result.setMessage("添加成功!");
		result.setCallbackType("closeCurrent");
		result.setNavTabId("show_equ_list");
		DwzAjaxResult.josnMessage(result);
	    } else {
		validateProperty(model);
		hsEquipmentInfoService.add(model);
		result.setStatusCode("200");
		result.setMessage("添加成功!");
		result.setCallbackType("closeCurrent");
		result.setNavTabId("show_equ_list");
		DwzAjaxResult.josnMessage(result);
	    }

	} catch (Exception e) {
	    result.setStatusCode("300");
	    result.setMessage("添加失败！" + e.getMessage());
	    DwzAjaxResult.josnMessage(result);
	    e.printStackTrace();
	}

    }

    /**
     * 通过id查询设备信息 跳转到编辑页面
     */
    public String findById() {
	Map request = (Map) ActionContext.getContext().get("request");
	Long editEquNo = (Long) request.get("equNo");
	HsEquipmentInfo equipment = hsEquipmentInfoService.getByEquNo(editEquNo);
	request.put("equipment", equipment);
	return "edit";
    }

    /**
     * 修改设备信息
     */
    public void editEqu() {
	HttpServletRequest request = ServletActionContext.getRequest();
	// 控制跳转
	DwzAjaxResult result = new DwzAjaxResult();
	try {
	    String schId = request.getParameter("sclId");
	    if (!ValidatorUtils.validateUUID(schId, false)) {
		throw new Exception("[学校编号]为空或不符合规范");
	    }
	    if (!ValidatorUtils.validateFixedLengthNumber(model.getEquType(), 1, false)) {
		throw new Exception("[设备类型]选择不符合规范");
	    }
	    HsSchoolInfo sch = hsSchoolInfoService.getById(schId);
	    // 设置设备信息的学校编号
	    model.setHsSchoolInfo(sch);
	    if ("0".equals(model.getEquType())) {
		validatePropertysByUpdate(model);
		hsEquipmentInfoService.update(model);
		result.setStatusCode("200");
		result.setMessage("保存成功!");
		result.setCallbackType("closeCurrent");
		result.setRel("show_equ_list");
		DwzAjaxResult.josnMessage(result);
	    } else {
		validatePropertysByUpdatePhone(model);
		// 设置跳转
		hsEquipmentInfoService.update(model);
		result.setStatusCode("200");
		result.setMessage("保存成功!");
		result.setCallbackType("closeCurrent");
		result.setRel("show_equ_list");
		DwzAjaxResult.josnMessage(result);
	    }
	} catch (Exception e) {
	    result.setStatusCode("300");
	    result.setMessage("保存失败!" + e.getMessage());
	    DwzAjaxResult.josnMessage(result);
	}

    }

    /**
     * 校验设备号
     * 
     * @throws IOException
     */
    public void selEquNo() {
	HttpServletRequest request = ServletActionContext.getRequest();
	String eno = request.getParameter("equNo");
	long eqno = Long.parseLong(eno);
	try {
	    List<HsEquipmentInfo> hsEqu = hsEquipmentInfoService.get(eqno);
	    HttpServletResponse resp = ServletActionContext.getResponse();
	    PrintWriter out = resp.getWriter();
	    if (hsEqu.size() == 0) {
		out.print("true");
	    } else {
		out.print("false");
	    }
	    out.flush();
	    out.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    private void validatePropertyByKaoQin(HsEquipmentInfo equ) throws Exception {

	if (!ValidatorUtils.validateFixedLengthNumber(equ.getEquAttInoutType(), 1, false)) {
	    throw new Exception("[考勤进出类型]为空或不符合规范");
	}
	if (!ValidatorUtils.validateFixedLengthNumber(equ.getEquNameDc(), 1, true)) {
	    throw new Exception("[硬件类型]输入不符合规范");
	}
	validateProperty(equ);
    }

    private void validateProperty(HsEquipmentInfo equ) throws Exception {
	validatePropertysByUpdatePhone(equ);
	if (!ValidatorUtils.validateFixedLengthNumber(equ.getEquStartDate(), 8, true)) {
	    throw new Exception("[设备安装时间]输入不符合规范");
	}
	
    }
    private void validatePropertysByUpdate(HsEquipmentInfo equ) throws Exception {
	validatePropertysByUpdatePhone(equ);
	if (!ValidatorUtils.validateFixedLengthNumber(equ.getEquAttInoutType(), 1, false)) {
	    throw new Exception("[考勤进出类型]为空或不符合规范");
	}
	if (!ValidatorUtils.validateFixedLengthNumber(equ.getEquNameDc(), 1, true)) {
	    throw new Exception("[硬件类型]输入不符合规范");
	}
    }
    private void validatePropertysByUpdatePhone(HsEquipmentInfo equ) throws Exception {
	if (!ValidatorUtils.validateNumber(equ.getEquNo() + "", 10, false)) {
	    throw new Exception("[设备流水号]为空或输入不符合规范");
	}
	if (!ValidatorUtils.validateFixedLengthNumber(equ.getEquStausFlag(), 1, true)) {
	    throw new Exception("[设备状态]输入不符合规范");
	}
	if (!ValidatorUtils.validateIP(equ.getEquSip(), true)) {
	    throw new Exception("[服务器端Ip]输入不符合规范");
	}
	if (!ValidatorUtils.validateNumber(equ.getEquSport(), 6, true)) {
	    throw new Exception("[服务器端口]输入不符合规范");
	}
	if (!ValidatorUtils.validateSafeString(equ.getEquApnSim(), 20, true)) {
	    throw new Exception("[设备通讯用APN卡号码]输入不符合规范");
	}
	if (!ValidatorUtils.validateSafeString(equ.getEquSoftVer(), 20, true)) {
	    throw new Exception("[设备软件版本号]输入不符合规范");
	}
	if (!ValidatorUtils.validateSafeString(equ.getEquHardVer(), 20, true)) {
	    throw new Exception("[设备硬件版本号]输入不符合规范");
	}
	if (!ValidatorUtils.validateRelativeSafeString(equ.getEquDescrip(), 100, true)) {
	    throw new Exception("[设备描述信息]不符合规范");
	}
	if (!ValidatorUtils.validateRelativeSafeString(equ.getRemark(), 200, true)) {
	    throw new Exception("[备注信息]不符合规范");
	}
    }
    public String getJsons() {
	return jsons;
    }

    public void setJsons(String jsons) {
	this.jsons = jsons;
    }

    public List<HsEquipmentInfo> getList() {
	return list;
    }

    public void setList(List<HsEquipmentInfo> list) {
	this.list = list;
    }

    public HsEquipmentInfo getEqu() {
	return equ;
    }

    public void setEqu(HsEquipmentInfo equ) {
	this.equ = equ;
    }

    public String getEquNos() {
	return equNos;
    }

    public void setEquNos(String equNos) {
	this.equNos = equNos;
    }

}
